﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;

namespace Sock
{
    class ClientServerThread
    {
        public TcpClient client;
        public NetworkStream ns;
        private BlockingQueue<string> list;
        ManageServerClients msc;
        ServerReadMessages srm;
        int i = 0;
        string c;

        public ClientServerThread(TcpClient client, ManageServerClients msc,int i)
        {
            this.client = client;
            ns = client.GetStream();
            this.msc = msc;
            this.i = i;
        }

        public void setC(string c)
        {
            this.c = c;
        }

        public void run() 
        {
            list = new BlockingQueue<string>();

            c = "guest_" + i;
            msc.addClient(c, this);
            srm = new ServerReadMessages(c, msc,this);
            Thread th = new Thread(new ThreadStart(srm.run));
            th.Start();
            try
            {
                while (client.Connected)
                {
                    string message = getMsg();
                    if (message.Trim().CompareTo("")!=0)
                    {
                        Byte[] sendBytes = Encoding.ASCII.GetBytes(message);
                        ns.Write(sendBytes, 0, sendBytes.Length);
                    }
                }
                Console.WriteLine("clentDeconectat1 : "+c);
                msc.removeClient(c);
                ns.Close();
                client.Close();
            }catch (System.IO.IOException)
            {
                Console.WriteLine("clentDeconectat2 : " + c);
                msc.removeClient(c);
                ns.Close();
                client.Close();
            }
        }
        public void putMsg(string s)
        {
            list.addString(s);
        }

        private string getMsg()
        {
            return list.getString();
        }
    }
}
